package com.pelli.imarket.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.util.AntPathMatcher;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class LoaderXmlServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private ResourceBundle bundle = ResourceBundle.getBundle("app");

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			String uri = req.getRequestURI();
			JSONObject json = new JSONObject();
			String tableName = req.getHeader("tableName");
			uri = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("."));
			System.out.println(uri);
			InputStream in = LoaderXmlServlet.class.getResourceAsStream(bundle
					.getString("grid"));

			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			ResourceBundle rb = ResourceBundle.getBundle("app");
			String grid = rb.getString("grid");
			// Collection<InputStream> xmls =
			// ResourceList.getResources("**/tableConfig.xml");
			// for (Iterator iterator = columns.iterator(); iterator.hasNext();)
			// {
			// InputStream columnConfig = (InputStream) iterator.next();
			//
			if (grid.startsWith("classpath:")) {
				grid = grid.substring("classpath:".length());
				if (!grid.startsWith("/")) {
					grid = new StringBuilder("/").append(grid).toString();
				}
			}
			Document doc = builder.parse(in);
			Node root = doc.getChildNodes().item(0);
			NodeList tables = root.getChildNodes();
			for (int i = 0; i < tables.getLength(); i++) {
				Node table = tables.item(i);
				switch (table.getNodeType()) {
				case Node.ELEMENT_NODE:
					if (table.getAttributes().getNamedItem("name")
							.getNodeValue().equals(tableName)) {
						Node nodeStore = table.getAttributes().getNamedItem("store");
						Node nodeRemote = table.getAttributes().getNamedItem("remote");
						NodeList columnsXml = table.getChildNodes();
						for (int j = 0; j < columnsXml.getLength(); j++) {
							Node columnsNode = columnsXml.item(j);
							switch (columnsNode.getNodeType()) {
							case Node.ELEMENT_NODE:
								
								NodeList columnList = columnsNode
										.getChildNodes();
								JSONArray columns = new JSONArray();
								for (int k = 0; k < columnList.getLength(); k++) {
									Node column = columnList.item(k);
									switch (column.getNodeType()) {
									case Node.ELEMENT_NODE:

										String id = column.getAttributes()
												.getNamedItem("id")
												.getNodeValue();
										System.out.println("id:" + id);
										String name = column.getAttributes()
												.getNamedItem("name")
												.getNodeValue();
										JSONObject jsoncolumn = new JSONObject();
										
										jsoncolumn.put("id", id);
										jsoncolumn.put("name", id);
										columns.put(jsoncolumn);
										// ColumnConfig cc = new
										// ColumnConfig(id,
										// name,
										// 200);
										// columns.add(cc);
										break;
									}
								}
								json.put("columns", columns);
								if(nodeStore!=null){
									json.put("store", nodeStore.getNodeValue());
									
								}
								if(nodeRemote!=null){
									json.put("remote", nodeRemote.getNodeValue());
								}
							}
						}
						
					}
					break;
				default:
					break;
				}
			}
			// }

			 OutputStream out = resp.getOutputStream();
			 out.write(json.toString().getBytes());
			// byte[] buffer = new byte[4096];
			// int ch = 0;
			// while ((ch = in.read(buffer)) > 0) {
			// out.write(buffer, 0, ch);
			//
			// }
			// in.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
